package com.cdp.zwy.zwy_manager_back_v1.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author zwy
 * @version 1.0
 * @description: 安全配置类
 * 角色：安保总指挥
 * @date 2025/8/17 15:55
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 1. 关闭 CSRF 和 CORS
        http.csrf(AbstractHttpConfigurer::disable)
                .cors(AbstractHttpConfigurer::disable); // 为了简化测试，暂时禁用CORS，后续可根据需要开启

        // 2. 配置会话管理为无状态 (STATELESS)，因为我们使用 JWT
        http.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        // 3. 配置请求授权规则
        http.authorizeHttpRequests(auth -> auth
                // 1. 首先，无条件放行所有 OPTIONS 预检请求
                .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()

                // 2. 其次，配置公开访问路径
                .requestMatchers("/login", "/register", "/files/**").permitAll()

                // 3. 然后，配置需要特定权限的路径
                .requestMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
                .requestMatchers("/employee/**").hasAuthority("ROLE_EMP")

                // 4. 最后，配置其他所有请求都需要认证
                .anyRequest().authenticated()


        );

        // 4. 将 JWT 过滤器添加到 Spring Security 过滤器链中
        // 确保它在处理用户名密码认证的过滤器之前执行
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}